<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="pd.queryParams.name" placeholder="请输入名称" clearable style="width: 150px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="pd.queryParams.mobile" placeholder="请输入手机号" clearable style="width: 150px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="更新时间" style="width: 290px">
            <el-date-picker
              v-model="dateRangeUpdateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['hrp:partner:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()" v-hasPermi="['hrp:partner:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()" v-hasPermi="['hrp:partner:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['hrp:partner:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.partnerList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" v-if="true" />
        <el-table-column label="名称" align="center" prop="name">
          <template #default="scope">
            <el-link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['wms:order:edit']">
              {{ scope.row.name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="编码" align="center" prop="code" />
        <el-table-column label="性别" align="center" prop="sex">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="mobile" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="固定电话" align="center" prop="telephone" />
        <el-table-column label="邮箱" align="center" prop="email" />
        <el-table-column label="标识" align="center" prop="logo" />
        <el-table-column label="网站地址" align="center" prop="website" />
        <el-table-column label="信用编码" align="center" prop="idCard" />
        <el-table-column label="成立日期" align="center" prop="birthday" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="评分" align="center" prop="score" />
        <el-table-column label="地址" align="center" prop="address" />
        <el-table-column label="是否客户" align="center" prop="isCustomer">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isCustomer ? '1' : '0' "/>
          </template>
        </el-table-column>
        <el-table-column label="是否供应商" align="center" prop="isSupplier">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isSupplier ? '1' : '0' "/>
          </template>
        </el-table-column>
        <el-table-column label="图片" align="center" prop="picture" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['wms:order:edit']"> 修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row.id)"
                        v-hasPermi="['wms:order:remove']">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="pd.total>0"
        :total="pd.total"
        v-model:page="pd.queryParams.pageNum"
        v-model:limit="pd.queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改客户对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="900px" append-to-body>
      <el-form ref="partnerFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="名称" prop="name">
              <el-input v-model="pd.form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="编码" prop="code">
              <el-input v-model="pd.form.code" placeholder="请输入编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="pd.form.sex" placeholder="请选择性别">
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.name" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="pd.form.mobile" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="pd.form.status">
                <el-radio v-for="dict in sys_status" :key="dict.value" :label="dict.value">{{dict.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="固定电话" prop="telephone">
              <el-input v-model="pd.form.telephone" placeholder="请输入固定电话" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="pd.form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标识" prop="logo">
              <el-input v-model="pd.form.logo" placeholder="请输入标识" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="网站地址" prop="website">
              <el-input v-model="pd.form.website" placeholder="请输入网站地址" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="信用编码" prop="idCard">
              <el-input v-model="pd.form.idCard" placeholder="请输入信用编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成立日期" prop="birthday">
              <el-date-picker clearable v-model="pd.form.birthday" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择成立日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="评分" prop="score">
              <el-input v-model="pd.form.score" placeholder="请输入评分" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地址" prop="address">
              <el-input v-model="pd.form.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否客户" prop="isCustomer">
              <el-radio-group v-model="pd.form.isCustomer">
                <el-radio v-for="dict in sys_yes_no" :label="dict.value == 1">{{dict.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否供应商" prop="isSupplier">
              <el-radio-group v-model="pd.form.isSupplier">
                <el-radio v-for="dict in sys_yes_no" :label="dict.value == 1">{{dict.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="图片" prop="picture">
              <el-input v-model="pd.form.picture" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Customer" lang="ts">
import {PartnerVO, listPartner, getPartner, delPartner, addPartner, updatePartner } from '@/views/hrp/partner/api';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_status, sys_user_sex, sys_yes_no } = toRefs<any>(proxy?.useDict('sys_status', 'sys_user_sex', 'sys_yes_no'));
const dateRangeUpdateTime = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const partnerFormRef = ref<ElFormInstance>();
const pd = reactive({
  partnerList: <PartnerVO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  ids: <Array<string | number>>([]),
  single: true,
  multiple: true,
  total: 0,
  form: <PartnerVO>{},
  queryParams: <PartnerVO>{
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    mobile: undefined,
    isCustomer: true,
    params: {
      updateTime: undefined,
    }
  },
  rules: <ElFormRules>{
    name: [{required: true, message: "名称不能为空", trigger: "blur"}],
    mobile: [{required: true, message: "手机号不能为空", trigger: "blur"}],
    status: [{required: true, message: "状态不能为空", trigger: "change"}],
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

// const { queryParams, form, rules } = toRefs(data);

/** 查询客户列表 */
async function getList() {
  pd.loading = true;
  pd.queryParams.params = {};
  proxy?.addDateRange(pd.queryParams, dateRangeUpdateTime.value, 'UpdateTime');
  const res = await listPartner(pd.queryParams);
  pd.partnerList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form = {};
  pd.form.isCustomer = true;
  pd.form.isSupplier = false;
  pd.form.status = '0';
  partnerFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangeUpdateTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: PartnerVO[]) {
  pd.ids = selection.map(item => item.id!);
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.visible = true;
  pd.dialog.title = "添加客户";
}

/** 修改按钮操作 */
async function handleUpdate(row?: PartnerVO) {
  reset();
  const _id = row?.id || pd.ids[0]
  const res = await getPartner(_id);
  Object.assign(pd.form, res.data);
  pd.dialog.visible = true;
  pd.dialog.title = "修改客户";
}

/** 提交按钮 */
function submitForm() {
  partnerFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updatePartner(pd.form).finally(() =>  pd.buttonLoading = false);
      } else {
        await addPartner(pd.form).finally(() =>  pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row?: PartnerVO) {
  const _ids = row?.id || pd.ids;
  await proxy?.$modal.confirm('是否确认删除客户编号为"' + _ids + '"的数据项？').finally(() => pd.loading = false);
  await delPartner(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('hrp/partner/export', {
    ...pd.queryParams
  }, `partner_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  pd.queryParams.isCustomer=true;
  pd.form.isCustomer=true
  getList();
});
</script>
